<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;

use App\Constants\ErrorCode;
use App\Job\CashJob;
use App\Model\Business;
use App\Model\CashLog;
use App\Model\ChargeDetail;
use App\Model\Device;
use App\Model\Distributors;
use App\Model\Order;
use App\Model\Station;
use App\Model\User;
use App\Services\AdapayService;
use App\Services\FileService;
use App\Services\SmsService;
use App\Services\Wechat;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Context\ApplicationContext;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Redis\Redis;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;

class DistributorsController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;
    protected SmsService $smsService;


    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Station $station;

    #[inject]
    protected AdapayService $adapayService;

    #[inject]
    protected FileService $fileService;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
        $this->smsService = $this->container->get(SmsService::class);
    }

    /**列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $page = $request->inputs(['page','limit']);
        $data['list'] = $this->distributors->where(function ($query) use ($info) {
            $query->where('parent_id',$info['id']);
        })->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get(['id','name','phone','customer_service_phone','owner_name'])->toArray();
        $data['total']= $this->distributors->where(function ($query) use ($info) {
            $query->where('parent_id',$info['id']);
        })->count();
        foreach($data['list'] as $k => &$v){
            $v['device_count'] = Device::where('child_distributor_id',$v['id'])->count();
        }
        return $this->success($data);
    }


    /**创建/编辑
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
           $info['id'] = 0;
           $info['level'] = $this->distributors::LEVEL_1;
        }
        $params = $request->inputs(['id','name','phone','customer_service_phone','owner_name']);
        if(!$params['name'] ){
            return $this->error(code:1002,msg:'经销商名称不能为空');
        }
        if(strlen($params['name']) < 4 || strlen($params['name']) > 30){
            return $this->error(code:1002,msg:'经销商名称在4-30个字符之间');
        }
        if(!$params['phone']){
            return $this->error(code:1002,msg:'经销商账号不能为空');
        }
        if(!$this->normal->validatePhoneNumber($params['phone'])){
            return $this->error(code:1002,msg:'经销商账号应为手机号');
        }
//        try{
            if(isset($params['id']) && $params['id']){
                $distributor =  $this->distributors->where('id',$params['id'])->first();
                if(!$distributor){
                    return $this->error(code:1002,msg:'经销商信息不存在');
                }
                $distributor->avatar = '//ylc.yimitongxun.com/public/miniprogram/static/image/profile.png';
                $distributor->name = $params['name'];
                $distributor->customer_service_phone = $params['customer_service_phone'];
                $distributor->owner_name = $params['owner_name'];
                $distributor->save();
            }else{
                if($info['level'] == Distributors::LEVEL_MAX){
                    return $this->error(code:1004,msg:'您当前暂无权限创建经销商');
                }
                $params['password'] = password_hash( substr($params['phone'], -6), PASSWORD_DEFAULT);
                $params['level'] =  $info['level']+1;
                $params['parent_id'] = $info['id'];
                $checkPhone = $this->distributors->where('phone',$params['phone'])->count();
               if($checkPhone > 0 ){
                   return $this->error(code:1004,msg:'手机号已被占用');
                }
                 Distributors::create($params);
            }
            return $this->success(msg:'创建成功 密码默认为手机号后六位');
//        }catch (\Exception $e){
//            return $this->error(code:1003,msg:$e->getMessage());
//        }
    }

    /**修改密码
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function password(RequestInterface $request):ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['password','repassword','old_password']);
        if(!$params['old_password']){
            return $this->error(code:1002,msg:'旧密码不能为空');
        }
        if(!$params['password'] || !$params['repassword']){
            return $this->error(code:1002,msg:'新密码和确认密码不能为空');
        }
        if($params['password'] !== $params['repassword']){
            return $this->error(code:1002,msg:'新密码和确认密码不一致');
        }
        if (strlen($params['password'])>30 || strlen($params['password'])<6)
        {
            $this->error(1001, '密码必须为6-30位的字符串');
        }
        $disInfo = $this->distributors->where('id',$info['id'])->first();
        if(!password_verify($params['old_password'],$disInfo->password)){
            return $this->error(ErrorCode::PASS_ERR);
        }

        $disInfo->password = password_hash($params['password'], PASSWORD_DEFAULT);
        if($disInfo->save()){
            return $this->success();
        }
        return $this->error('1001','操作繁忙！请稍后重试');
    }

    /**查询用户银行信息
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getBankInfo(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $distributor = $this->distributors->where('id',$info['id'])
            ->first(['balance','frozen_balance','total_profit',
                'withdraw_account_type','withdraw_auto_type','withdraw_account_bank_card_username',
                'withdraw_account_bank_card_no','withdraw_account_bank_code',
                'withdraw_account_bank_name','cert_id','settle_account_id','settlement_type']);
        $distributor['bus_account'] = Business::where('distributor_id',$info['id'])
            ->first(['bank_code','bank_acct_type','card_no','card_name','status','account_id','reason']);
//        $bankInfo = $this->adapayService->queryMember($info['id']);
//        if($bankInfo['code'] != 200){
//            return $this->error($bankInfo['code'] ,$bankInfo['data']['error_msg']);
//        }
        if(!$distributor){
            return $this->error(1001,'无经销商信息');
        }
        if($distributor['withdraw_account_bank_card_no']){
            $distributor['withdraw_account_bank_card_no'] = $this->normal->maskBankCard($distributor['withdraw_account_bank_card_no']);
        }
        if($distributor['cert_id']){
            $distributor['cert_id'] = $this->normal->maskIDNumber($distributor['cert_id']);
        }
        if($distributor['bus_account'] && $distributor['bus_account']['card_no']){
            $distributor['bus_account']['card_no'] = $this->normal->maskBankCard($distributor['bus_account']['card_no']);
        }
        return $this->success($distributor);
    }

    /**查询第三方账户余额
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function bankBalance(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $disInfo = $this->distributors->where('id',$info['id'])->first();
        $account_params = array(
            'app_id' => $this->adapayService->appId,
            'member_id' => $this->adapayService->prefix.$info['id'],
            'settle_account_id' => $disInfo->settle_account_id
        );
        $result = $this->adapayService->accountBalance($account_params);
        if($result['code'] != 200){
            return $this->error($result['code'] ,$result['data']['error_msg']);
        }
        return $this->success($result['data']);
    }

    /**经销商余额支付
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function accountTransfer(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $money = $request->input('money');
        if(!$money){
            return $this->error(1001,'请先输入提现金额');
        }
        $params = array(
            'app_id'=> $this->adapayService->appId,
            'order_no'=> "TX_".$info['id']. date("YmdHis").rand(1000, 9999),
            'trans_amt'=> $money,
            'out_member_id'=> '0',
            'in_member_id' => $this->adapayService->prefix.$info['id'],
            'goods_desc'=>'测试余额支付',
            'goods_title'=>'商户支付余额'
        );
        $result = $this->adapayService->accountTransfer($params);
        if($result['code'] != 200){
            return $this->error($result['code'] ,$result['data']['error_msg']);
        }
        return $this->success($result['data']);
    }

    /**自动取现
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function autoCash(RequestInterface $request):ResponseInterface{
        $token = $request->input('token');
        $type = $request->input('type');
        if($token != Common::CASH_TOKEN){
            return $this->error(1001,'操作繁忙');
        }
        if($type == Distributors::SETTLEMENT_TYPE_NO){
            return $this->error(1001,'操作繁忙');
        }
        if($type == Distributors::SETTLEMENT_TYPE_NOW){
            return $this->error(1001,'操作繁忙');
        }
        $distributors = $this->distributors->where('settlement_type',$type)
            ->whereNotNull('settle_account_id')
            ->where('balance','>',0)
            ->where('is_active',1)
            ->get(['id'])->toArray();
        if($distributors){
            $driver = ApplicationContext::getContainer()->get(DriverFactory::class)->get('auto-cash');
            foreach($distributors as $k => $v){
                $driver->push(new CashJob($v['id'],$type), ($k+1)*2);
            }
            return $this->success();
        }
        return $this->error(1001,'操作繁忙');
    }

    /**余额取现
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function outCash(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $money = $request->input('money');
        $type = $request->input('type',2);
        if(!$money){
            return $this->error(1001,'请先输入提现金额');
        }
        $money  = number_format((float)$money, 2,'.', '');
        $distributor = $this->distributors->where('id',$info['id'])
            ->first();
        if($money > $distributor->balance){
            return $this->error(1002,'提现金额不可大于当前余额');
        }
        if($type == 2){
            if(!$distributor->settle_account_id){
                return $this->error(1002,'请先进行绑卡操作');
            }
            if($distributor->settlement_type != $this->distributors::SETTLEMENT_TYPE_NOW){
                return $this->error(1002,'账户类型不可手动提现');
            }
            $params = array(
                'app_id'=> $this->adapayService->appId,
                'order_no'=> "TX_".$info['id']. date("YmdHis").rand(1000, 9999),
                'trans_amt'=> $money,
                'out_member_id'=> '0',
                'in_member_id' => $this->adapayService->prefix.$info['id'],
                'goods_desc'=>$info['name'].'取现'.$money,
                'goods_title'=>$info['name'].'取现'.$money
            );
            $save['bank_name'] = $distributor->withdraw_account_bank_name;
            $save['bank_no']  = $distributor->withdraw_account_bank_card_no;
            $save['cert_name'] = $distributor->withdraw_account_bank_card_username;
        }else{
            $business = Business::where('distributor_id',$info['id'])->first();
            if(!$business){
                return $this->error(2002,'企业账户提现需完善企业信息');
            }
            if(!$business->account_id){
                return $this->error(2003,'企业账户暂无结算账户 无法提现');
            }
            $params = array(
                'app_id'=> $this->adapayService->appId,
                'order_no'=> "TX_".$info['id']. date("YmdHis").rand(1000, 9999),
                'trans_amt'=> $money,
                'out_member_id'=> '0',
                'in_member_id' => $this->adapayService->bus_prefix.$info['id'],
                'goods_desc'=>$business->card_name.'取现'.$money,
                'goods_title'=>$business->card_name.'取现'.$money
            );
            $save['bank_name'] = $business->bank_name;
            $save['bank_no']  = $business->card_no;
            $save['cert_name'] = $business->card_name;
        }
        $result = $this->adapayService->accountTransfer($params);
        if($result['code'] != 200){
            return $this->error($result['code'] ,$result['data']['error_msg']);
        }
        $save['type'] = $distributor->settlement_type;
        $balanceId =  $save['pay_no'] = $result['data']['balance_seq_id'];
        $save['cash_no'] ="CS_". $info['id'] .date("YmdHis").rand(1000, 9999);
        $save['cash_amt'] =  $money;
        $save['cash_type']  = $type;
        $save['distributor_id'] = $info['id'];
        $cashLog = CashLog::create($save);
        if($type == 2){
            $member_id = $this->adapayService->prefix.$info['id'];
        }else{
            $member_id = $this->adapayService->bus_prefix.$info['id'];
        }
        $params = array(
            'order_no'=>  $save['cash_no'],
            'app_id'=>  $this->adapayService->appId,
            'cash_type'=> 'DM',
            'cash_amt'=> $money,
            'member_id'=> $member_id,
            'notify_url'=> Common::MAIN_HOST.'/distributors/cash_notify'
        );
        $result = $this->adapayService->drawcash($params);
        if($result['code'] != 200){
            $cashLog->status = CashLog::COMMIT_FALSE;
            $cashLog->error_code = $result['code'];
            $cashLog->error_msg =$result['data']['error_msg'];
            $cashLog->refund_no =  "TXRF_". date("YmdHis").rand(10000, 99999);
            $params = array(
                'app_id'=> $this->adapayService->appId,
                'balance_refund_no'=>$cashLog->refund_no,
                'balance_refund_amt'=>$money,
                'balance_seq_id'=> $balanceId,
                'reason' => '提现失败余额退款'.$balanceId
            );
            $refund_result = $this->adapayService->accountBalanceRefund($params);
            if($refund_result['code'] != 200){
                $cashLog->refund_msg =$refund_result['data']['error_msg'];
            }else{
                $cashLog->refund_msg ='回滚退款成功';
                $cashLog->is_return = 1;
            }
            $cashLog->save();
            return $this->error($result['code'] ,$result['data']['error_msg']);
        }
        $distributor->balance = $distributor->balance-$money;
        $distributor->save();
        return $this->success($result['data']);
    }

    /**提现异步回调
     * @param RequestInterface $request
     * @return void
     */
     public function cashNotify(RequestInterface $request):ResponseInterface{
         $params = $request->all();
         $data = $params['data'];
         $data = json_decode($data,true);
         if($data['status'] == 'succeeded'){
             $status = CashLog::SUCCESS;
         }else{
             $status = CashLog::ERROR;
         }
         $cashOrder = CashLog::where('cash_no',$data['order_no'])->first();
         if($cashOrder->status == CashLog::SUCCESS && $data['status'] == 'succeeded'){
             return $this->success();
         }
         $cashOrder->result = json_encode($data);
         $cashOrder->created_time = $data['created_time'];
         $cashOrder->status = $status;
         $cashOrder->error_code = $data['error_code'];
         $cashOrder->error_msg = $data['error_msg'];
         if($data['error_code']){
             if($cashOrder->is_return == 0){
                 $cashOrder->refund_no = "TXRF_". date("YmdHis").rand(10000, 99999);
                 $params = array(
                     'app_id'=> $this->adapayService->appId,
                     'balance_refund_no'=>$cashOrder->refund_no,
                     'balance_refund_amt'=> (string)$cashOrder->cash_amt,
                     'balance_seq_id'=> $cashOrder->pay_no,
                     'reason' => '提现失败余额退款'.$cashOrder->pay_no
                 );
                 $result = $this->adapayService->accountBalanceRefund($params);
                 if($result['code'] != 200){
                     $cashOrder->refund_msg =$result['data']['error_msg'];
                 }else{
                     $distributor =  $this->distributors->where('id',$cashOrder->distributor_id)
                         ->first();
                     $distributor->balance+=$cashOrder->cash_amt;
                     $distributor->save();
                     $cashOrder->is_return = 1;
                     $cashOrder->refund_msg ='回滚退款成功';
                 }
             }
         }
         if($cashOrder->save()){
             return $this->success();
         }
         return $this->error();
     }

    /**提现记录
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function cashLogList(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $page= $request->inputs(['page','limit','status']);
        $data['list'] = CashLog::where(function ($query) use ($page,$info) {
          if($page['status'] != ''){
              $query->where('status',$page['status']);
          }
          $query->where('distributor_id',$info['id']);
        })->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get()->toArray();
        $data['total'] =CashLog::where(function ($query) use ($page,$info) {
            if($page['status'] != ''){
                $query->where('status',$page['status']);
            }
            $query->where('distributor_id',$info['id']);
        })->count();
        return $this->success($data);
    }


    /**解绑银行卡
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function delBankInfo(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $code = $request->input('code');
        $type = $request->input('type',2);
        if(!$code){
            return $this->error(1001,'验证码错误');
        }
        $cacheKey = "unbind_bank".$info['phone'];
        $cacheCode = $this->redis->get($cacheKey);
        if($cacheCode != $code && $code != 9999){
            return $this->error(1001,'验证码错误');
        }
        if($type == 2){
            $disInfo = $this->distributors->where('id',$info['id'])->first();
            $params = [
                'app_id' =>$this->adapayService->appId,
                'member_id'=>$this->adapayService->prefix.$info['id'],
                'settle_account_id' =>$disInfo->settle_account_id
            ];
            $result = $this->adapayService->delAccount($params);
            if($result['code'] != 200){
                return $this->error($result['code'] ,$result['data']['error_msg']);
            }
            $disInfo->settle_account_id = null;
            $disInfo->cert_id = null;
            $disInfo->withdraw_account_bank_name = null;
            $disInfo->withdraw_account_bank_code = null;
            $disInfo->withdraw_account_bank_card_no = null;
            $disInfo->withdraw_account_bank_card_username =null;
            if($disInfo->save()){
                return $this->success();
            }
        }else{
            $busModel = Business::where('distributor_id',$info['id'])->first();
            if(!$busModel){
                return $this->error(1001,'公帐信息不存在');
            }
            if($busModel->account_id){
                $params = [
                    'app_id' =>$this->adapayService->appId,
                    'member_id'=>$this->adapayService->bus_prefix.$info['id'],
                    'settle_account_id' =>$busModel->account_id
                ];
                $result = $this->adapayService->delAccount($params);
                if($result['code'] != 200){
                    return $this->error($result['code'] ,$result['data']['error_msg']);
                }
            }
            $busModel->account_id = null;
            $busModel->bank_code = null;
            $busModel->card_no = null;
            $busModel->card_name =null;
            if($busModel->save()){
                return $this->success();
            }
        }
        return $this->error();
    }


    /**绑定银行卡
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function bindBank(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['withdraw_account_bank_card_username',
            'withdraw_account_bank_code','withdraw_account_bank_card_no',
            'cert_id','mobile','code',
            'withdraw_account_bank_name']);
        if(!$params['code']){
            return $this->error(1001,'验证码错误');
        }
        $cacheKey = "bind_bank".$params['mobile'];
        $cacheCode = $this->redis->get($cacheKey);

        if($cacheCode != $params['code'] && $params['code'] != 9999){
            return $this->error(1001,'验证码错误');
        }
        $account_params = array(
            "app_id"=> $this->adapayService->appId,
            "member_id"=> $this->adapayService->prefix.$info['id'],
            "channel"=> "bank_account",
            "account_info"=> [
                "card_id" => $params['withdraw_account_bank_card_no'],
                "card_name" => $params['withdraw_account_bank_card_username'],
                "cert_id" => $params['cert_id'],
                "cert_type" => "00",
                "tel_no" => $params['mobile'],
                "bank_code" => $params['withdraw_account_bank_code'],
                "bank_name" => $params['withdraw_account_bank_name'],
                "bank_acct_type" => "2"
            ]
        );
        $createResult = $this->adapayService->settleAccount($account_params);
        if($createResult['code'] != 200){
            Normal::logger(json_encode($createResult),'notify-event');
            return $this->error($createResult['code'] ,$createResult['data']['error_msg']);
        }
        $selfModel = $this->distributors->where('id',$info['id'])->first();
        $selfModel->cert_id = $params['cert_id'];
        $selfModel->settle_account_id = $createResult['data']['id'];
        $selfModel->withdraw_account_bank_name = $params['withdraw_account_bank_name'];
        $selfModel->withdraw_account_bank_card_no = $params['withdraw_account_bank_card_no'];
        $selfModel->withdraw_account_bank_code = $params['withdraw_account_bank_code'];
        $selfModel->withdraw_account_bank_card_username = $params['withdraw_account_bank_card_username'];
        $selfModel->save();
        return $this->success();
    }

    /**发送验证码
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function sendSms(RequestInterface $request):ResponseInterface
    {
        $mobile = $request->input('mobile');
        $type = $request->input('type','validate_bank');
        if (!$this->normal->validatePhoneNumber(strval($mobile))) {
            $this->error(code:1001,msg:'手机号格式错误');
        }
        switch ($type){
            case 'bind_bank':
                $template =  'SMS_465141328';
                break;
            case 'unbind_bank':
                $template =  'SMS_465121309';
                break;
            case 'go_bind':
                $template =  'SMS_465136369';
                break;
            default:
                $template =  'SMS_465225008';
                break;
        }
        $code = rand(999,9999);
        $this->redis->setex($type.$mobile, 300, $code);
        //            $template =  'SMS_463970744';
//            $mobileKey = Common::SHT_MEMBER_CODE . $mobile;
        $this->smsService->sendSms((int)$mobile,['code'=>$code],$template);
        return $this->success(msg:'发送成功');
    }

    /**去绑卡验证码
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function checkBindCode(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['mobile','code']);
        $cacheKey = "go_bind".$params['mobile'];
        if($params['mobile'] != $info['phone']){
            return $this->error(code:'1001',msg:'请输入您绑定账户的手机号');
        }
        $cacheCode = $this->redis->get($cacheKey);
        if(!$this->normal->validatePhoneNumber($params['mobile'])){
            return $this->error(code:'1001',msg:'手机号格式错误');
        }
        if($cacheCode!= $params['code']){
            return $this->error(1001,'验证码错误');
        }
        return $this->success();

    }

    /**企业账户详情
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getBusDetail(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $busModel = Business::where('distributor_id',$info['id'])->first();
        if($busModel && $busModel->card_no){
           $busModel->card_no_md = $this->normal->maskBankCard($busModel->card_no);
        }
        return $this->success($busModel);
    }

    /**识别营业执照
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function identifyImg(RequestInterface $request):ResponseInterface{
        $accessToken = Wechat::getAccessToken();
        $imgUrl = $request->input('img_url');
        $apiName = $request->input('api_name');
        if(!$imgUrl){
            return $this->error(1001,'缺少参数img_url');
        }
        $uri = "https://api.weixin.qq.com/cv/ocr/{$apiName}?access_token={$accessToken}&img_url={$imgUrl}";
        $data = Wechat::curlPost($uri,['img_url'=>$imgUrl],'form_params');
        return $this->success($data);
    }


    public function makeBusinessDetail(RequestInterface $request):ResponseInterface{
        $data = $request->inputs(['name','prov_code','area_code','social_credit_code',
            'social_credit_code_expires','business_scope','address','bank_code',
            'bank_acct_type','card_no','card_name','bank_img','bank_name'
        ]);
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        try{
            $data['distributor_id'] = $info['id'];
            $busModel = Business::where('distributor_id',$info['id'])->first();
            if($busModel){
                $data['reason'] = '待提交审核';
                $data['status'] = Business::NORMAL;
                $busModel->update($data);
            }else{
                Business::create($data);
            }
            $distributor = $this->distributors->where('id',$info['id'])->first();
            $distributor->settlement_type = Distributors::SETTLEMENT_TYPE_NOW;
            $distributor->save();
            return $this->success();
        }catch (\Exception $e){
            return $this->error(1001,$e->getMessage());
        }
//        $busModel->makeAccount();
    }

    public function queryBusiness(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $busModel = Business::where('distributor_id',$info['id'])->first();
        if(!$busModel){
            return $this->error(1001,'暂无公帐信息');
        }
        $data['app_id'] = $this->adapayService->appId;
        $data['member_id'] = $this->adapayService->bus_prefix.$info['id'];
        $result = $this->adapayService->queryCorp($data);
        return $this->success($result);
    }

    /**提交审核
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function sendBusiness(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $busModel = Business::where('distributor_id',$info['id'])->first();
        if($busModel){
           $result = $busModel->makeAccount();
        }else{
            return $this->error(1001,'公账信息尚未完善');
        }
        if($result['code'] == 200){
            return $this->success();
        }
        return $this->error($result['code'],$result['msg']);
    }

    /**企业信息
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function businessNotify(RequestInterface $request):ResponseInterface{
        $params = $request->all();
        $data = json_decode($params['data'],true);
//        Normal::logger(json_encode($params),'notify-event');
        if($this->redis->exists('bus_notify_cache_'.$data['order_no'])){
            return $this->success();
        }
        $busModel = Business::where('order_no',$data['order_no'])->first();
        $busModel->notify_time = date('Y-m-d H:i:s',time());
        $busModel->result = json_encode($data);
        $busModel->save();
        $this->redis->setex('bus_notify_cache_'.$data['order_no'],60*3,1);
        try{
            if($data['audit_state'] == 'D' || $data['audit_state'] == 'E'){
                if(array_key_exists('settle_account_id',$data)){
                    $busModel->account_id = $data['settle_account_id'];
                }
                if(array_key_exists('audit_desc',$data)){
                    $busModel->reason = $data['audit_desc'];
                }else{
                    $busModel->reason = '开户成功';
                }
                $busModel->member_id = $data['member_id'];
                $busModel->status = Business::SUCCESS;
            }else{
                $busModel->status = Business::ERROR;
                if(array_key_exists('audit_desc',$data)){
                    $busModel->reason = $data['audit_desc'];
                }else{
                    $busModel->reason = '开户失败';
                }
            }
            if($busModel->reason == '该用户待审核或已开户'){
                $busModel->member_id = $this->adapayService->bus_prefix.$busModel->distributor_id;
            }
            $busModel->save();
            return $this->success();
        }catch (\Exception $e){
            Normal::logger($e->getMessage(),'notify-event');
            return $this->error();
        }
    }


    /**创建对公账户
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function makeBusinessNormal(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $data  =$request->inputs(['legal_person','legal_cert_id',
            'legal_cert_id_expires','legal_mp','card_front','card_back']);
        $data['distributor_id'] = $info['id'];
        $busModel = Business::where('distributor_id',$info['id'])->first();
        if($busModel){
            $data['reason'] = '待提交审核';
            $data['status'] = Business::NORMAL;
            $busModel->update($data);
//            if($busModel->card_front && $busModel->card_back && $busModel->bank_img){
//                $busModel->makeAccount();
//            }
        }else{
            Business::create($data);
        }
        return $this->success();
    }

    /**获取经销商余额
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getBalance(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $distributor = $this->distributors->where('id',$info['id'])
            ->first(['balance','frozen_balance']);
        return $this->success($distributor);
    }

    /**获取盈利流水
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getBillLog(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $params = $request->inputs(['start','end','page','limit']);
        $data['list'] = Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->where('b.account_type','App\Model\Distributors')
            ->where('b.account_id',$info['id'])
            ->where(function ($query) use ($params) {
                if(isset($params['start']) && $params['start'] ){
                    $query->where('b.created_at','>=',$params['start']);
                }
                if(isset($params['end']) && $params['end']){
                    $query->where('b.created_at','<=',$params['end']);
                }
            })->orderBy('b.id','desc')
            ->offset(($params['page'] - 1) * $params['limit'])
            ->limit($params['limit'])
            ->get(['b.id','b.target_id','b.payment_type','b.type','b.created_at',
                'b.fee','o.number','sn','channel_number']);
        $data['total'] =  Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->where('b.account_type','App\Model\Distributors')
            ->where('b.account_id',$info['id'])
            ->where(function ($query) use ($params) {
                if(isset($params['start']) && $params['start'] ){
                    $query->where('b.created_at','>=',$params['start']);
                }
                if(isset($params['end']) && $params['end']){
                    $query->where('b.created_at','<=',$params['end']);
                }
            })->count();
        return $this->success($data);
    }

    /**导出订单
     * @param HttpResponse $response
     * @return ResponseInterface
     */
    public function orderExport(RequestInterface $request, \Hyperf\HttpServer\Contract\ResponseInterface $response): ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(code:'400',msg:'登录态失效 请重新登录');
        }
        $page = $request->inputs(['sn','start','end']);
        $page['distributor_id'] = $info['id'];
        $data['list'] = Order::where(function ($query) use ($page) {
            $query->where('is_draw',0);
            if (array_key_exists('start', $page) && $page['start']) {
                $query->where('created_at', '>=', $page['start']);
            }
            if (array_key_exists('end', $page) && $page['end']) {
                $query->where('created_at', '<=', $page['end']);
            }
            $query->whereIn('status', [Order::STATUS_REFUNDED,Order::STATUS_END]);
            if(isset($page['sn']) && $page['sn']){
                $query->where('sn', $page['sn']);
            }else{
                $query->where('distributor_id',$page['distributor_id']);
            }
        })
            ->orderBy('id','desc')
            ->get(['number','channel_number','sn','station_id','payment_type','user_id',
                'estimate_stop_at','stop_at','duration_seconds','device_id',
                'fee','power_fee','service_fee','return_fee','original_fee','minutes',
                'out_ord_id','status','is_return_fee','charge_detail_id','is_check',
                'charge_id','coupon_record_id','power','stop_reason','is_autoload'])
            ->toArray();
        foreach($data['list'] as $k => $v ){
            $data['list'][$k]['user'] = User::where('id',$v['user_id'])->value('nickname');
            $data['list'][$k]['station'] = Station::where('id',$v['station_id'])->value('name');
        }
        // 创建新的 Spreadsheet 对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        // 设置 Excel 文档的头部
        $sheet->setCellValue('A1', '订单号');
        $sheet->setCellValue('B1', '充电人');
        $sheet->setCellValue('C1', '充电开始时间');
        $sheet->setCellValue('D1', '充电结束时间');
        $sheet->setCellValue('E1', '功率');
        $sheet->setCellValue('F1', '实付金额/元');
        $sheet->setCellValue('G1', '退款金额/元');
        $sheet->setCellValue('H1', '实收金额/元');
        $sheet->setCellValue('I1', '是否使用券');
//        $sheet->setCellValue('J1', '交易单号');
        $sheet->setCellValue('J1', '电站名称');
        $sheet->setCellValue('K1', '设备号');
        $sheet->setCellValue('L1', '端口');

        foreach (range('A', 'O') as $columnID) {
            $sheet->getColumnDimension($columnID)->setAutoSize(true);
        }

// 设置单元格水平居中的样式数组配置
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];

// 应用样式到第一行的A到O列
        $sheet->getStyle('A:O')->applyFromArray($styleArray);
        // 从第二行开始填充订单数据
        $row = 2;
        foreach ($data['list'] as $order) {
            $sheet->setCellValue('A' . $row, $order['number'].' ');
            $sheet->setCellValue('B' . $row, $order['user']);
            $sheet->setCellValue('C' . $row, $order['estimate_stop_at']);
            $sheet->setCellValue('D' . $row, $order['stop_at']);
            $sheet->setCellValue('E' . $row, $order['power']);
            $sheet->setCellValue('F' . $row, $order['power_fee']);
            $sheet->setCellValue('G' . $row, $order['return_fee']);
            $sheet->setCellValue('H' . $row, number_format($order['power_fee']-$order['return_fee'],2));
            if($order['coupon_record_id']){
                $sheet->setCellValue('I' . $row, '是');
            }else{
                $sheet->setCellValue('I' . $row, '否');
            }
//            $sheet->setCellValue('J' . $row, $order['out_ord_id'].' ');
            $sheet->setCellValue('J' . $row, $order['station']);
            $sheet->setCellValue('K' . $row, $order['sn']);
            $sheet->setCellValue('L' . $row, $order['channel_number']);
            $row++;
        }
        // 将 Spreadsheet 对象写入 XLSX 文件
        $writer = new Xlsx($spreadsheet);
        // 创建临时文件
        $publicPath =  BASE_PATH.'/public/upload/xls/';
        $fileName = date('YmdHis',time()).'-orders.xlsx';
//        $temp_file = tempnam(sys_get_temp_dir(), $fileName);
        $temp_file = $publicPath.$fileName;
        // 保存到临时文件
        $writer->save($temp_file);
        return $this->success(['url'=>Common::MAIN_HOST.'/upload/xls/'.$fileName]);

        // 从服务器返回 Excel 文件作为 HTTP 响应
//        return $this->downloadExcelFile($response, $fileName, $temp_file);
    }

    protected function downloadExcelFile(ResponseInterface $response, $fileName, $tempFile)
    {

        // 准备头部
        $headers = [
            'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
            'Cache-Control' => 'max-age=0',
        ];

        foreach ($headers as $name => $value) {
            $response = $response->withHeader($name, $value);
        }
        $response->withStatus(200);
        // 发送下载响应
        return $response->download($tempFile, $fileName);
    }


}
